package com.powerbank.device.controller;

import com.powerbank.device.dto.DeviceStatusDTO;
import com.powerbank.device.dto.SlotStatusDTO;
import com.powerbank.device.service.EnhancedDeviceCommunicationService;
import com.powerbank.device.service.DeviceHeartbeatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 设备控制API
 */
@Slf4j
@RestController
@RequestMapping("/device")
public class DeviceController {

    @Autowired
    private EnhancedDeviceCommunicationService deviceCommunicationService;

    @Autowired
    private DeviceHeartbeatService heartbeatService;

    /**
     * 发送开锁指令
     */
    @PostMapping("/unlock/{deviceCode}/{slotNo}")
    public String unlockDevice(@PathVariable String deviceCode, 
                              @PathVariable Integer slotNo) {
        log.info("接收开锁指令 - 设备: {}, 插槽: {}", deviceCode, slotNo);
        
        String commandId = deviceCommunicationService.sendUnlockCommand(deviceCode, slotNo);
        if (commandId != null) {
            return "指令发送成功，指令ID: " + commandId;
        } else {
            return "指令发送失败";
        }
    }

    /**
     * 发送锁定指令
     */
    @PostMapping("/lock/{deviceCode}/{slotNo}")
    public String lockDevice(@PathVariable String deviceCode, 
                            @PathVariable Integer slotNo) {
        log.info("接收锁定指令 - 设备: {}, 插槽: {}", deviceCode, slotNo);
        
        String commandId = deviceCommunicationService.sendLockCommand(deviceCode, slotNo);
        if (commandId != null) {
            return "指令发送成功，指令ID: " + commandId;
        } else {
            return "指令发送失败";
        }
    }

    /**
     * 查询设备状态
     */
    @GetMapping("/status/{deviceCode}")
    public DeviceStatusDTO getDeviceStatus(@PathVariable String deviceCode) {
        log.info("查询设备状态 - 设备: {}", deviceCode);
        
        // 先从缓存获取
        DeviceStatusDTO status = deviceCommunicationService.getCachedDeviceStatus(deviceCode);
        
        if (status == null) {
            // 缓存中没有，发送查询指令
            String commandId = deviceCommunicationService.queryDeviceStatus(deviceCode);
            if (commandId != null) {
                // 等待查询结果
                boolean success = deviceCommunicationService.waitForCommandCompletion(commandId, 10);
                if (success) {
                    status = deviceCommunicationService.getCachedDeviceStatus(deviceCode);
                }
            }
        }
        
        return status;
    }

    /**
     * 查询插槽状态
     */
    @GetMapping("/slot-status/{deviceCode}/{slotNo}")
    public SlotStatusDTO getSlotStatus(@PathVariable String deviceCode, 
                                      @PathVariable Integer slotNo) {
        log.info("查询插槽状态 - 设备: {}, 插槽: {}", deviceCode, slotNo);
        
        // 先从缓存获取
        SlotStatusDTO status = deviceCommunicationService.getCachedSlotStatus(deviceCode, slotNo);
        
        if (status == null) {
            // 缓存中没有，发送查询指令
            String commandId = deviceCommunicationService.querySlotStatus(deviceCode, slotNo);
            if (commandId != null) {
                // 等待查询结果
                boolean success = deviceCommunicationService.waitForCommandCompletion(commandId, 10);
                if (success) {
                    status = deviceCommunicationService.getCachedSlotStatus(deviceCode, slotNo);
                }
            }
        }
        
        return status;
    }

    /**
     * 批量查询设备状态
     */
    @PostMapping("/batch-status")
    public String batchQueryStatus(@RequestBody String[] deviceCodes) {
        log.info("批量查询设备状态 - 设备数量: {}", deviceCodes.length);
        
        int successCount = deviceCommunicationService.batchQueryDeviceStatus(deviceCodes);
        return String.format("批量查询完成，成功发送 %d/%d 个查询指令", successCount, deviceCodes.length);
    }

    /**
     * 检查设备是否在线
     */
    @GetMapping("/online/{deviceCode}")
    public boolean isDeviceOnline(@PathVariable String deviceCode) {
        return !heartbeatService.isDeviceOffline(deviceCode);
    }

    /**
     * 获取设备最后心跳时间
     */
    @GetMapping("/heartbeat/{deviceCode}")
    public Long getLastHeartbeat(@PathVariable String deviceCode) {
        return heartbeatService.getLastHeartbeatTime(deviceCode);
    }

    /**
     * 获取指令执行结果
     */
    @GetMapping("/command-result/{commandId}")
    public String getCommandResult(@PathVariable String commandId) {
        return deviceCommunicationService.getCommandResult(commandId);
    }

    /**
     * 取消指令
     */
    @PostMapping("/cancel-command/{commandId}")
    public String cancelCommand(@PathVariable String commandId) {
        boolean success = deviceCommunicationService.cancelCommand(commandId);
        return success ? "指令取消成功" : "指令取消失败";
    }
}